package com.lj.uc.service.impl;

import com.lj.uc.service.model.MySession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.Set;

/**
 * Created by dave_suwei on 2017/12/25.
 */
@Service
public class MySessionManagerImpl {
    private static Logger logger = LoggerFactory.getLogger(MySessionManagerImpl.class);

    @Value("${session.expireTime}")
    private String expireTimeStr;


    private Hashtable<String,MySession> sessionHashMap;
    private long expireTime;//过期时间

    public Hashtable<String, MySession> getSessionHashMap() {
        return sessionHashMap;
    }

    @PostConstruct
    public void init(){
        this.expireTime= 1000*60*20;
        try{this.expireTime= Long.parseLong(expireTimeStr);}catch (Exception ex){}
        sessionClean();
    }

    public MySessionManagerImpl() {
        this.sessionHashMap=new Hashtable<>();
    }

    public MySessionManagerImpl(long expireTime) {
        this.expireTime = expireTime;
        this.sessionHashMap=new Hashtable<>();
    }

    public void setSession(String sessionId, MySession session){
        this.sessionHashMap.put(sessionId,session);
    }
    public MySession getSession(String sessionId){
        return this.sessionHashMap.get(sessionId);
    }

    public long getExpireTime() {
        return expireTime;
    }

    public void setExpireTime(long expireTime) {
        this.expireTime = expireTime;
    }
    private void sessionClean(){//session清理方法
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (true){
                    //System.out.println("清理过期session");
                    //遍历session清理过期session
                    long ctime= System.currentTimeMillis();//获取当前时间
                    Set<String> keys=sessionHashMap.keySet();
                    Iterator<String> keyI= keys.iterator();
                    while (keyI.hasNext()){
                        String key=keyI.next();
                        MySession session=sessionHashMap.get(key);
                        if(session.getUpdateTime()+expireTime<ctime){//已经过期的session
                            sessionHashMap.remove(key);//移除
                            logger.debug("清理过期session->"+key);
                        }
                    }
                    try {
                        Thread.sleep(1000);//休眠一秒
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }).start();
    }
}
